/*
 * @lc app=leetcode.cn id=501 lang=javascript
 *
 * [501] 二叉搜索树中的众数
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var findMode = function(root) {
    let result = {}

    function nextRoot(root) {
        if (!root) {
            return 
        }

        result[root.val] = ( result[root.val] ?? 0 ) + 1

        if (root.left) {
            nextRoot(root.left)
        }
        if (root.right) {
            nextRoot(root.right)
        }
    }
    nextRoot(root)

    let maxNum = 0
    let resultArr = []
    Object.keys(result).map(e => {
        if (result[e] === maxNum) {
            resultArr.push(Number(e))
        }
        if (result[e] > maxNum) {
            maxNum = result[e]
            resultArr = [ Number(e) ]
        }
    })
    return resultArr
};
// @lc code=end

